package session

import "bytes"

type textWriter struct {
	output      bytes.Buffer
	indent      int
	lineStart   bool
}

var indentStrings = []string{"", "    "}

func getIndentString(level int) string {
	if level >= len(indentStrings) {
		indentStrings = append(indentStrings, getIndentString(level-1) + indentStrings[1])
	}
	return indentStrings[level]
}

func (w *textWriter) write(p []byte) {
	if len(p) > 0 {
		if w.lineStart {
			w.output.WriteString(getIndentString(w.indent))
			w.lineStart = false
		}
		w.output.Write(p)
	}
}

func (w *textWriter) writeString(s string) {
	if len(s) > 0 {
		if w.lineStart {
			w.output.WriteString(getIndentString(w.indent))
			w.lineStart = false
		}
		w.output.WriteString(s)
	}
}

func (w *textWriter) writeCode(lang string, s string){
	w.writeString("```")
	w.writeString(" ")
	w.writeString(lang)
	w.writeLine()
	w.writeString(s)
	w.writeLine()
	w.writeString("```")
	w.writeLine()
}

func (w *textWriter) writeCodeFunc(lang string, f func()){
	w.writeString("```")
	w.writeString(" ")
	w.writeString(lang)
	w.writeLine()
	f()
	w.writeLine()
	w.writeString("```")
	w.writeLine()
}

func (w *textWriter) writeLine() {
	w.output.WriteString("\n")
	w.lineStart = true


}

func (w *textWriter) ensureAtNewLine() {
	if !w.lineStart {
		w.writeLine()
	}
}

func (w *textWriter) increaseIndent() {
	w.indent++
}

func (w *textWriter) decreaseIndent() {
	w.indent--
}

func (w *textWriter) string() string {
	return w.output.String()
}

func (w *textWriter) bytes() []byte {
	return w.output.Bytes()
}